package com.lh.glorypavilion.handler;

import com.lh.glorypavilion.exception.glorypavilionEx;
import com.lh.glorypavilion.result.R;
import com.lh.glorypavilion.result.ResultCode;
import com.lh.glorypavilion.util.ExceptionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常处理
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class CustomExceptionHandler {

    //sql语句异常
    @ExceptionHandler(BadSqlGrammarException.class)
    public R sqlError(BadSqlGrammarException e){
        //e.printStackTrace();
        log.info(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCode.BAD_SQL_GRAMMAR);
    }

    //json格式异常
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R jsonError(HttpMessageNotReadableException e){
        //e.printStackTrace();
        log.info(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCode.JSON_PARSE_ERROR);
    }

    //其他未知异常
    @ExceptionHandler(Exception.class)
    public R error(Exception e){
        //e.printStackTrace();
        log.info(ExceptionUtils.getMessage(e));
        return R.setResult(ResultCode.UNKNOWN_REASON);
    }

    //自定义异常
    @ExceptionHandler(glorypavilionEx.class)
    public R customError(glorypavilionEx e){
        log.error(ExceptionUtils.getMessage(e));
        return R.error().message(e.getMessage()).code(e.getCode());
    }
}
